package com.TinyBBS.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.TinyBBS.bean.Review;
import com.TinyBBS.bean.User;
import com.TinyBBS.db.DBCRUD;
import com.TinyBBS.db.PageableResultSet;

public class ReviewModel {
	private DBCRUD crud = null;
	private ResultSet rs = null;
	private PageableResultSet prs = null;

	public ReviewModel() {
		crud = new DBCRUD();
		prs = new PageableResultSet();
	}
	/**
	 * 
	 * @return
	 */
	public List<Review> getAllReview() {
		List<Review> reviewList = new ArrayList<Review>();
		try {
			rs = crud.fetchAll("review");
			while (rs.next()) {
				Review review = new Review();
				review.setId(rs.getInt("id"));
				review.setTitle(rs.getString("title"));
				review.setContent(rs.getString("content"));
				review.setPostDate(rs.getDate("postdate"));
				review.setUser_id(rs.getInt("user_id"));
				review.setGame_id(rs.getInt("game_id"));
				reviewList.add(review);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return reviewList;
	}
	/**
	 * 
	 * @param gameId
	 * @return
	 */
	public List<Review> getReviewListByGameId(int gameId) {
		List<Review> reviewList = new ArrayList<Review>();
		try {
			rs = crud.fetchAll("review r,user u", "r.game_id = " + "'" + gameId + "'" +" and u.id = r.user_id");
			while (rs.next()) {
				Review review = new Review();
				review.setId(rs.getInt("id"));
				review.setTitle(rs.getString("title"));
				review.setContent(rs.getString("content"));
				review.setPostDate(rs.getDate("postdate"));
				review.setUser_id(rs.getInt("user_id"));
				review.setGame_id(rs.getInt("game_id"));
				review.setAuthor(rs.getString("username"));
				reviewList.add(review);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return reviewList;
	}

	/**
	 * 
	 * @param review
	 * @return
	 */
	public boolean insertReview(Review review) {
		Map<String, Object> mp = new HashMap<String, Object>();
		mp.put("title", review.getTitle());
		mp.put("content", review.getContent());
		mp.put("postdate", review.getPostDate());
		mp.put("user_id", review.getUser_id());
		mp.put("game_id", review.getGame_id());
		
		if (crud.insert("review", mp)) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * Remove review
	 * @param id
	 * @return boolean true if deleted successfully, else false
	 */
	public boolean removeReview(String id){
		return crud.delete("review", "id = " + "'" + id + "'");
	}

}
